package Springboot.Inceptor;

import Springboot.Utils.JwtHelper;
import Springboot.Utils.Result;
import Springboot.Utils.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * 添加拦截器，在添加删除修改新闻之前检查token是否过期，意在检查用户是否登录
 * 通过request来接收请求头中的token数据来进行验证
 * 如果未登录，需要向前端发送json数据，但是无法直接发送
 * 需要将json数据转化成字符串类型的数据，通过response来发送
 * */
@Component
public class loginInceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean expiration = jwtHelper.isExpiration(token);
        if(expiration) {
            Result<Object> build = Result.build(null, ResultCodeEnum.NOTLOGIN);;
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(build);
            response.getWriter().write(json);
            return false;
        }
        return true;
    }
}
